from django.core.management.base import BaseCommand
from django.db import transaction

from home.models import Jobposting, JobCategories
from user.models import City, Company, HRInfo, User, Role


class Command(BaseCommand):
    help = "Seed 10 Java + 10 Python job postings with minimal dependencies"

    def add_arguments(self, parser):
        parser.add_argument('--city', type=str, default='深圳市')
        parser.add_argument('--company', type=str, default='深圳科技有限公司')
        parser.add_argument('--hr', type=str, default='系统HR')
        parser.add_argument('--extra', action='store_true', help='再额外生成各10条且内容不同')

    @transaction.atomic
    def handle(self, *args, **options):
        city_name = options['city']
        company_name = options['company']
        hr_name = options['hr']

        # 准备依赖数据
        role, _ = Role.objects.get_or_create(name='hr')
        user, _ = User.objects.get_or_create(phone='19900000000', defaults={
            'username': hr_name,
            'role': role,
            'status': True,
        })
        city, _ = City.objects.get_or_create(name=city_name)
        company, _ = Company.objects.get_or_create(name=company_name, defaults={
            'logo': '', 'job_number': 100, 'boss_number': 10, 'is_listed': 0,
            'employee_number': 1000, 'description': '', 'location': city_name, 'city': city,
        })
        hrinfo, _ = HRInfo.objects.get_or_create(user=user, defaults={
            'name': hr_name, 'company': company,
        })
        cate_java, _ = JobCategories.objects.get_or_create(name='后端开发')
        cate_java3, _ = JobCategories.objects.get_or_create(name='Java开发', pid=cate_java)
        cate_py, _ = JobCategories.objects.get_or_create(name='后端开发')
        cate_py3, _ = JobCategories.objects.get_or_create(name='Python开发', pid=cate_py)

        def create_job(title: str, label: str, desc: str, money: str, cate: JobCategories):
            Jobposting.objects.create(
                title=title,
                money=money,
                type=2,
                working=3,
                education='本科',
                label=label,
                description=desc,
                city=city,
                hr=hrinfo,
                company=company,
                jobcate=cate,
            )

        java_desc = '负责后端业务开发与性能优化，掌握Spring生态与MySQL，熟悉分布式与缓存。'
        py_desc = '负责后端接口与数据处理，熟悉Django/Flask与MySQL，了解异步与缓存。'

        for i in range(1, 11):
            create_job(
                title=f"Java后端工程师（{i}）",
                label="Java,Spring,MySQL,Redis",
                desc=java_desc,
                money="20-30K",
                cate=cate_java3,
            )
        for i in range(1, 11):
            create_job(
                title=f"Python后端工程师（{i}）",
                label="Python,Django,MySQL,Redis",
                desc=py_desc,
                money="18-28K",
                cate=cate_py3,
            )

        # 可选：再额外各10条，不同的标签/薪资/经验/描述，确保内容差异
        if options.get('extra'):
            # 准备更强差异化的模板（行业/职责/技术栈/薪资/学历/经验/城市/公司）
            cities = [city_name, '北京市', '上海市', '杭州市', '成都市']
            companies = [company_name, '字节跳动', '阿里巴巴', '腾讯科技', '美团']

            java_templates = [
                {"title": "Java分布式架构师", "label": "Java,SpringCloud,Dubbo,Nacos,Sentinel", "money": "35-55K", "working": 5, "edu": "本科", "desc": "主导金融级分布式系统架构设计，落地服务治理与容灾演练，支撑千万级QPS。"},
                {"title": "广告投放后端(Java)", "label": "Java,ClickHouse,Redis,Kafka,Flink", "money": "30-45K", "working": 4, "edu": "本科", "desc": "负责广告计费与实时归因链路，建设高吞吐埋点采集与明细核对平台。"},
                {"title": "电商交易平台后端", "label": "Java,ShardingSphere,MySQL,Redis,RocketMQ", "money": "28-42K", "working": 4, "edu": "本科", "desc": "重构订单/支付/库存中心，拆分单体为微服务，支持大促秒杀与风控。"},
                {"title": "IoT设备云平台后端", "label": "Java,MQTT,Netty,TSDB,OpenTelemetry", "money": "26-40K", "working": 3, "edu": "本科", "desc": "承接千万设备接入，设计长连接与遥测数据入湖，完善链路追踪与监控。"},
                {"title": "SRE/平台工程(Java)", "label": "Java,Kubernetes,Operator,Helm,ArgoCD", "money": "30-50K", "working": 5, "edu": "硕士", "desc": "研发应用运维一体化平台，落地灰度/回滚/弹性扩缩容与成本优化。"},
                {"title": "风控引擎后端", "label": "Java,RuleEngine,GraphDB,Redis,Canal", "money": "28-40K", "working": 4, "edu": "本科", "desc": "建设规则引擎与图谱关联分析，实时识别欺诈与薅羊毛行为。"},
                {"title": "音视频后端(Java)", "label": "Java,WebRTC,CDN,FFmpeg,Quic", "money": "30-48K", "working": 4, "edu": "本科", "desc": "搭建低延时互动直播服务，点播转码分发与边缘缓存加速。"},
                {"title": "地图服务后端", "label": "Java,GeoHash,ElasticSearch,VectorTile", "money": "26-38K", "working": 3, "edu": "本科", "desc": "建设POI检索与路径规划服务，支持矢量瓦片与地理围栏能力。"},
                {"title": "数据中台后端(Java)", "label": "Java,OLAP,Lakehouse,Iceberg,CDC", "money": "32-46K", "working": 4, "edu": "本科", "desc": "统一指标口径，构建数据服务网关，打通ODS/DWD/ADS分层。"},
                {"title": "跨境支付后端", "label": "Java,PCI-DSS,分账,清结算,多币种", "money": "33-50K", "working": 5, "edu": "本科", "desc": "搭建多币种清结算平台，合规对接清算网络与风控系统。"},
            ]

            py_templates = [
                {"title": "数据科学工程师(Python)", "label": "Python,Pandas,PyTorch,Airflow,MLFlow", "money": "28-45K", "working": 3, "edu": "硕士", "desc": "建设特征工程与训练流水线，沉淀实验追踪与模型注册。"},
                {"title": "NLP算法工程师", "label": "Python,Transformers,Qwen,NLP,RAG", "money": "30-48K", "working": 4, "edu": "硕士", "desc": "构建知识检索增强问答，优化召回/重排与提示工程策略。"},
                {"title": "数据平台后端(Python)", "label": "Python,FastAPI,SQLAlchemy,ClickHouse,Redis", "money": "26-40K", "working": 3, "edu": "本科", "desc": "开发数据门户与指标API，治理数据血缘与权限体系。"},
                {"title": "爬虫与反爬工程师", "label": "Python,Scrapy,Playwright,Proxy,AntiBot", "money": "24-36K", "working": 3, "edu": "本科", "desc": "搭建高并发采集集群，规避反爬规则并保证数据质量。"},
                {"title": "MLOps工程师", "label": "Python,TensorRT,ONNX,Ray,Serving", "money": "30-46K", "working": 4, "edu": "本科", "desc": "落地模型服务化与弹性推理，降低GPU成本与时延。"},
                {"title": "BI数据工程师", "label": "Python,ETL,Airbyte,dbt,Metabase", "money": "22-33K", "working": 2, "edu": "本科", "desc": "建设ETL流水线与指标看板，支持多源异构数据同步。"},
                {"title": "风控策略平台(Python)", "label": "Python,Rule,FeatureStore,Redis,Graph", "money": "28-42K", "working": 4, "edu": "本科", "desc": "实现策略配置与灰度实验，沉淀特征仓与标签体系。"},
                {"title": "知识图谱工程师", "label": "Python,Neo4j,RDF,Embedding,Triples", "money": "27-40K", "working": 3, "edu": "硕士", "desc": "构建实体关系抽取与图谱存储，服务风控与推荐场景。"},
                {"title": "后台服务开发(Python)", "label": "Python,Django,Celery,PostgreSQL,AsyncIO", "money": "24-38K", "working": 3, "edu": "本科", "desc": "开发异步任务与消息编排，优化数据库索引与性能。"},
                {"title": "计算机视觉工程师", "label": "Python,OpenCV,YOLO,Diffusion,CUDA", "money": "30-48K", "working": 4, "edu": "硕士", "desc": "研发目标检测与图像生成，优化推理吞吐与精度。"},
            ]

            # 逐条写入，分布到不同城市/公司
            for idx, tpl in enumerate(java_templates, start=11):
                c_obj, _ = City.objects.get_or_create(name=cities[idx % len(cities)])
                comp_obj, _ = Company.objects.get_or_create(name=companies[idx % len(companies)], defaults={
                    'logo': '', 'job_number': 50, 'boss_number': 5, 'is_listed': 0,
                    'employee_number': 500, 'description': '', 'location': c_obj.name, 'city': c_obj,
                })
                Jobposting.objects.create(
                    title=tpl['title'],
                    money=tpl['money'],
                    type=2,
                    working=tpl['working'],
                    education=tpl['edu'],
                    label=tpl['label'],
                    description=tpl['desc'],
                    city=c_obj,
                    hr=hrinfo,
                    company=comp_obj,
                    jobcate=cate_java3,
                )

            for idx, tpl in enumerate(py_templates, start=11):
                c_obj, _ = City.objects.get_or_create(name=cities[(idx+1) % len(cities)])
                comp_obj, _ = Company.objects.get_or_create(name=companies[(idx+1) % len(companies)], defaults={
                    'logo': '', 'job_number': 60, 'boss_number': 6, 'is_listed': 0,
                    'employee_number': 600, 'description': '', 'location': c_obj.name, 'city': c_obj,
                })
                Jobposting.objects.create(
                    title=tpl['title'],
                    money=tpl['money'],
                    type=2,
                    working=tpl['working'],
                    education=tpl['edu'],
                    label=tpl['label'],
                    description=tpl['desc'],
                    city=c_obj,
                    hr=hrinfo,
                    company=comp_obj,
                    jobcate=cate_py3,
                )

        msg = 'Seeded 10 Java + 10 Python jobs.'
        if options.get('extra'):
            msg = 'Seeded 20 Java + 20 Python jobs (extra enabled).'
        self.stdout.write(self.style.SUCCESS(msg))


